/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sma;

import java.lang.*;
import java.io.*;
import java.sql.SQLException;
import java.sql.ResultSet;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import jade.core.*;
import jade.core.behaviours.*;
import jade.domain.*;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.FIPANames.InteractionProtocol;
import jade.lang.acl.*;
import jade.content.*;
import jade.content.onto.*;
import jade.proto.AchieveREInitiator;
import jade.proto.AchieveREResponder;
import sma.ontology.*;
import sma.gui.*;
import java.util.*;
/**
 *
 * @author guity
 */
public class ScoutCoordinatorAgent extends Agent{
    
  private AuxInfo game;
//  private sma.ontology.InfoGame game;
  
  private AID coordinatorAgent;
  private AID scoutAgent;
//  private AID scoutcoordinatorAgent;
  public ScoutCoordinatorAgent() {
  }

  /**
   * A message is shown in the log area of the GUI
   * @param str String to show
   */
  private void showMessage(String str) {
    System.out.println(getLocalName() + ": " + str);
  }


  /**
   * Agent setup method - called when it first come on-line. Configuration
   * of language to use, ontology and initialization of behaviours.
   */
  protected void setup() {

    /**** Very Important Line (VIL) *********/
    this.setEnabledO2ACommunication(true, 1);
    /****************************************/

    // Register the agent to the DF
    ServiceDescription sd1 = new ServiceDescription();
    sd1.setType(UtilsAgents.SCOUTCOORDINATOR_AGENT);
    sd1.setName(getLocalName());
    sd1.setOwnership(UtilsAgents.OWNER);
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.addServices(sd1);
    dfd.setName(getAID());
    try {
      DFService.register(this, dfd);
      showMessage("Registered to the DF");
    }
    catch (FIPAException e) {
      System.err.println(getLocalName() + " registration with DF " + "unsucceeded. Reason: " + e.getMessage());
      doDelete();
    }

    // search  Coordinator
//    ServiceDescription searchCriterion = new ServiceDescription();
//    searchCriterion.setType(UtilsAgents.COORDINATOR_AGENT);
//    this.coordinatorAgent = UtilsAgents.searchAgent(this, searchCriterion);
//     searchAgent is a blocking method, so we will obtain always a correct AID
    
    // search Scout 
  //  searchCriterion.setType(UtilsAgents.SCOUT_AGENT);
  //  this.scoutAgent = UtilsAgents.searchAgent(this, searchCriterion);
    // searchAgent is a blocking method, so we will obtain always a correct AID

    MessageTemplate mt = MessageTemplate.MatchProtocol(UtilsAgents.PROTOCOL_TURN);
    this.addBehaviour(new QueriesReceiver(this, mt));
    
  }   
  

  class QueriesReceiver extends AchieveREResponder {
		
		/* (non-Javadoc)
		 * @see jade.proto.AchieveREResponder#prepareResponse(jade.lang.acl.ACLMessage)
		 */
		@Override
		protected ACLMessage prepareResponse(ACLMessage arg0) throws NotUnderstoodException, RefuseException {
			ACLMessage response = arg0.createReply();

			try {
				if (arg0.getContentObject() instanceof AuxInfo) {
					response.setPerformative(ACLMessage.AGREE);
					game = (AuxInfo) arg0.getContentObject();
					   coordinateScouts();
					
				} else if (arg0.getPerformative() == ACLMessage.AGREE) {
					response = null;
				} else {
					throw new NotUnderstoodException("Not the expected object type");
				}
			} catch (UnreadableException e) {
				response.setPerformative(ACLMessage.FAILURE);
			}
			 showMessage("Get information");
                     
			return response;
		}

		/* (non-Javadoc)
		 * @see jade.proto.AchieveREResponder#prepareResultNotification(jade.lang.acl.ACLMessage, jade.lang.acl.ACLMessage)
		 */
		@Override
		protected ACLMessage prepareResultNotification(ACLMessage arg0, ACLMessage arg1) throws FailureException {
			return null;
		}

		/* (non-Javadoc)
		 * @see jade.proto.AchieveREResponder#handleRequest(jade.lang.acl.ACLMessage)
		 */
		@Override
		protected ACLMessage handleRequest(ACLMessage arg0) throws NotUnderstoodException, RefuseException {
			try {
				Object objectReceived = arg0.getContentObject();
				if (objectReceived instanceof AuxInfo) {
					// Is the coordinator informing of a new turn
					game = (AuxInfo) objectReceived;
                                        showMessage("Stablished Communication");

					// Find all my agents and send them the new turn
					ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
					for (int x = 0; x < game.getMap().length; x++) {
						for (int y = 0; y < game.getMap()[x].length; y++) {
							Cell c = game.getCell(x, y);
							if (c!=null)
								if (c.isThereAnAgent()) {
									InfoAgent a = c.getAgent();
									if (a.getAgent().equals("S")) {
										message.addReceiver(a.getAID());
									}
								}
						}
					}
					message.setProtocol(UtilsAgents.PROTOCOL_TURN);
					message.setSender(this.myAgent.getAID());
					message.setContentObject(game);//getInfo() added <---- :-D
					this.myAgent.send(message);
				}
				
			} catch (UnreadableException e) {
				showMessage("Received an Object that cannot be understood");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			showMessage("Sent information");
			return super.handleRequest(arg0);
		}

		public QueriesReceiver(Agent arg0, MessageTemplate arg1) {
			super(arg0, arg1);
		}
	}
  public void coordinateScouts(){
    int[]  oldpositionsX=new int[game.getNumScouts()];
    int[]  oldpositionsY=new int[game.getNumScouts()];  
   int i = 0;
   for (int x = 0; x < game.getMap().length; x++) {
						for (int y = 0; y < game.getMap()[x].length; y++) {
							Cell c = game.getCell(x, y);
							if (c!=null)
								if (c.isThereAnAgent() && c.getAgent().getAgentType()==0) {
                                                                    oldpositionsX[i]= c.getColumn();
                                                                    oldpositionsY[i]= c.getRow();
                                                                    i++;
                                                                  } 
                                            
  
                                                }
    }
               showMessage("askfmalskdfjal"+Arrays.toString(oldpositionsX));
  }
}

